package com.hzit.loan.repayment.controller;

import com.hzit.loan.pay.commonApi.enums.PayChannelEnum;
import com.hzit.loan.pay.commonApi.enums.PayWayEnum;
import com.hzit.loan.pay.commonApi.req.PayReq;
import com.hzit.loan.pay.commonApi.resp.PayResultData;
import com.hzit.loan.pay.commonApi.resp.RespVo;
import com.hzit.loan.pay.commonApi.utils.IdWorker;
import com.hzit.loan.pay.commonApi.utils.PayDigestUtil;
import com.hzit.loan.repayment.config.RepaymentConfig;
import com.hzit.loan.repayment.iClient.ILoanPayClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/repay")
@RestController
public class RepaymentController {

    @Autowired
    private ILoanPayClient loanPayClient;

    int count = 1;


    @Autowired
    private RepaymentConfig repaymentConfig;


    @RequestMapping("/to")
    public String toRepay(){

        //调用支付服务，pay/create接口

        //1.封装网银支付接口所需要的参数

        PayReq payReq = new PayReq();

        payReq.setUserId("test01"); //TODO
        payReq.setPayChannel(PayChannelEnum.ALIPAY.getCode());
        payReq.setPayWay(PayWayEnum.ALIPAY_SM.getCode());
        payReq.setMchId(repaymentConfig.getMchId());
        payReq.setOrderAmount("100");
        IdWorker worker = new IdWorker(1,1,1);
        payReq.setMchOrderId(String.valueOf(worker.nextId())); //分布式环境下全局唯一id。雪花算法

        payReq.setIp("127.0.0.1");
        payReq.setCcy("cny");
        payReq.setBody("测试订单");
        payReq.setDetail("测试");
        payReq.setAttach("");
        payReq.setDeviceInfo("");


        String MD5Salt = repaymentConfig.getReqkey();


        //通过签名算法计算
        String sign = null;
        try {
            sign = PayDigestUtil.getSign(payReq,MD5Salt);
            System.out.println("sign = "+ sign );

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        payReq.setSign(sign); //签名

        //调用支付服务的支付接口
        RespVo<PayResultData > respVo = loanPayClient.netBankPay(payReq);

        if(respVo.getCode() != 0){
            System.out.println("调用支付服务失败："+ respVo.getMsg());
            return  "";
        }

        //验证签名

        PayResultData payResultData =  respVo.getData();
        //获取支付地址
        System.out.println("payUrl = " + payResultData.getPayUrl());

        //跳转支付页面

        //


        return "";
    }


}
